/**
 * @Project Name:cola-code-generate
 * @Package Name:cn.hoofungson.framework.cola.code.generate.util
 * @Since JDK 1.8
 */

package cn.hoofungson.qycp.code.generate.util;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @Description: FreemarkerUtils
 * @Author 胡松 hoofungson@163.com
 * @Date 2022-06-16 14:04
 * @Version V1.0
 */
public class FreemarkerUtils {

    private FreemarkerUtils() {
    }

    /**
     * 生成文件
     *
     * @param ftlPath
     * @param templateName
     * @param dataModel
     * @param toPath
     * @param toFileName
     **/
    public static void generateFile(String ftlPath
            , String templateName
            , Object dataModel
            , String toPath
            , String toFileName) throws IOException, TemplateException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_29);
        configuration.setDirectoryForTemplateLoading(new File(ftlPath));
        configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_29));
        Template template = configuration.getTemplate(templateName);

        // 校验输出目录，如果不存在则新建目录
        File directory = new File(toPath);
        if (!directory.exists()) directory.mkdirs();
        FileWriter fileWriter = new FileWriter(toPath + "\\" + toFileName);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        template.process(dataModel, bufferedWriter);
        bufferedWriter.flush();
        fileWriter.close();
    }
}
